// Keyword
function refreshDropdown(dropdown) {
    var text = dropdown.find('textarea').val();
    dropdown.find('.dropdown-option').each(function () {
        var option = $$(this);
        if (text.indexOf(option.children('span').text()) >= 0) {
            option.addClass('selected');
        } else {
            option.removeClass('selected');
        }
    });
}

$$(document).on('change', '.input-dropdown textarea', function () {
    refreshDropdown($$(this).parents('.input-dropdown'));
});
$$(document).on('click', '.input-dropdown a.dropdown-toggle', function () {
    var dropdown = $$(this).parents('.input-dropdown'),
        input = dropdown.find('textarea');
    if (!input.prop('disabled')) {
        dropdown.toggleClass('dropdown-open');
    }
});
$$(document).on('click', '.input-dropdown .dropdown-option', function () {
    var option = $$(this),
        text = option.children('span').text();
    var dropdown = option.parents('.input-dropdown'),
        input = dropdown.find('textarea'),
        val = input.val();

    if (option.hasClass('selected')) {
        var newVal = val.replace(new RegExp(',?' + text, 'g'), '');
        if (newVal.startWith(',')) {
            newVal = newVal.substr(1);
        }
        option.removeClass('selected');
        input.val(newVal).change();
    } else {
        var newVal = val ? (val + ',' + text) : text;
        option.addClass('selected');
        input.focus().val(newVal).blur().change();
    }

    //if (input.length === 1) {
    //    var textarea = input[0];
    //    var val = input.val(),
    //        newVal = val ? (val + ',' + text) : text,
    //        selectionStart = newVal.length,
    //        selectionEnd = newVal.length;
    //
    //    input.val(newVal).change();
    //    if (textarea.createTextRange) {
    //        var range = textarea.createTextRange();
    //        range.collapse(true);
    //        range.moveStart('character', selectionStart);
    //        range.moveEnd('character', selectionEnd);
    //        range.select();
    //    } else if (textarea.setSelectionRange) {
    //        textarea.focus();
    //        textarea.setSelectionRange(selectionStart, selectionEnd);
    //        textarea.blur();
    //    }
    //}

});
$$(document).on('click', function (e) {
    var clicked = $$(e.target);
    if (!clicked.hasClass('dropdown-toggle') && clicked.parents('.dropdown-toggle').length === 0) {
        if (!clicked.hasClass('dropdown-option') && clicked.parents('.dropdown-option').length === 0) {
            $$('.input-dropdown').removeClass('dropdown-open');
        }
    }
});

// user & depart select
$$(document).on('click', '.custom-select', function (e) {
    var el = $$(this),
        input = el.find('input'),
        selectType = input.attr('select-type');

    if (input.prop('disabled')) {
        return;
    }

    var view = el.parents('.' + myApp.params.viewClass)[0] && el.parents('.' + myApp.params.viewClass)[0].f7View;
    if (!view) {
        return;
    }

    if (selectType == 'users') {
        var callbackName = $$.uniqueName();
        var users = input.data('users');
        window[callbackName] = {
            selectedUsers: users,
            delegate: function (users) {
                var values = [], names = [];
                $$.each(users, function (id, user) {
                    values.push(user.id);
                    names.push(user.name);
                });
                input.val(values.join('，'));
                input.data('users', users);
                el.find('.item-after').text(names.join('，'));
            }
        };

        view.router.load({url: (myApp.padApp ? 'selectUser-pad.html' : 'selectUser.html') + '?delegate=' + callbackName});
    } else if (selectType == 'departs') {
        var callbackName = $$.uniqueName();
        var departs = input.data('departs');
        window[callbackName] = {
            selectedDeparts: departs,
            delegate: function (departs) {
                console.log('selected' + departs);
                var values = [], names = [];
                $$.each(departs, function (id, depart) {
                    values.push(depart.id);
                    names.push(depart.title);
                });
                input.val(values.join('，'));
                input.data('departs', departs);
                el.find('.item-after').text(names.join('，'));
            }
        };


        view.router.load({url: (myApp.padApp ? 'selectDepart-pad.html' : selectDepart.html) + '?delegate=' + callbackName});
    } else if (selectType == 'meeting-users') {
        var list = el.parents('form'),
            names = el.find('.item-after').text(),
            ids = list.find('input[name="personIds"]').val();
        var callbackName = $$.uniqueName();

        var array1 = ids.split(','),
            array2 = names.split(',');
        var users = {};
        for (var i = 0; i < array1.length; i++) {
            var id = array1[i];
            if (id.length > 0) {
                users[id] = {
                    "id": id,
                    "firstName": array2[i]
                };
            }
        }
        window[callbackName] = {
            selectedUsers: users,
            delegate: function (users) {
                var values = [], names = [];
                $$.each(users, function (id, user) {
                    values.push(user.id);
                    names.push(user.name);
                });
                list.find('input[name="personIds"]').val(values.join(','));
                input.val(names.join(','));
                el.find('.item-after').text(names.join(','));
            }
        };

        view.router.load({url: (myApp.padApp ? 'selectUser-pad.html' : 'selectUser.html') + '?delegate=' + callbackName});
    } else if (selectType == 'meeting-room') {
        var list = el.parents('form'),
            beginInput = list.find('input[name="beginTime"]'),
            endInput = list.find('input[name="endTime"]');
        var beginTime = beginInput.val(),
            endTime = endInput.val();

        if (!beginTime || !endTime) {
            myApp.toast('请选择开始结束时间', '<div>×</div>', {}).show(true);
            return;
        } else if (beginTime >= endTime) {
            myApp.toast('结束时间必须大于开始时间', '<div>×</div>', {}).show(true);
            return;
        }

        //beginTime = beginTime.replace('T', ' ');
        //endTime = endTime.replace('T', ' ');

        var ms = Date.parse(beginTime.replace(/-/g, '/'));
        if (!isNaN(ms)) {
            beginTime = new Date(ms).Format('yyyy-MM-dd hh:mm');
        }
        ms = Date.parse(endTime.replace(/-/g, '/'));
        if (!isNaN(ms)) {
            endTime = new Date(ms).Format('yyyy-MM-dd hh:mm');
        }

        var callbackName = $$.uniqueName();
        var roomId = input.val();
        window[callbackName] = {
            selectedRoom: roomId,
            delegate: function (room) {
                list.find('input[name="roomId"]').val(room.roomId);
                input.val(room.roomName);
                el.find('.item-after').text(room.roomName);
            }
        };

        view.router.load({url: 'selectRoom.html?' + $$.serializeObject({delegate: callbackName, beginTime: beginTime, endTime: endTime})});
    }
});

function buildHandleUserInput(el, data, name) {
    var li = el.parents('li'),
        checkboxLi = li.parents('ul').find('input[name="isPushMessage"]').parents('li');
    if (data.isend) {
        el.children().remove();
        li.hide();
        checkboxLi.hide();
    } else {
        li.show();
        checkboxLi.show();
    }

    var view = el.parents('.' + myApp.params.viewClass)[0] && el.parents('.' + myApp.params.viewClass)[0].f7View;
    if (!view) {
        return;
    }

    function updateUsers(users) {
        el.children().remove();
        $$.each(users, function (id, user) {
            el.append('<label class="label-checkbox">'
                + '<input type="checkbox" name="' + name + '" value="' + id + '" checked="checked" disabled>'
                + '<div class="form-checkbox"><img src="'+ user.avatar +'">' + user.name + '</div>'
                + '</label>');
        });
        if (el.children().length == 0) {
            el.append('<a href="#" class="button button-select-user">点击选择处理人</a>');
        } else {
            el.append('<label class="label-checkbox button-select-user">'
                + '<div class="form-checkbox"><img src="image/icon-add-user.png">添加</div>'
                + '</label>');
        }

        el.find('.button-select-user').click(function () {
            var callbackName = $$.uniqueName();
            //var users = {};
            window[callbackName] = {
                selectedUsers: users,
                delegate: updateUsers
            };

            view.router.load({url: (myApp.padApp ? 'selectUser-pad.html' : 'selectUser.html') + '?delegate=' + callbackName});
        });
    }

    if (data.selectUserMode === 'singleUser') {
        el.children().remove();
        $$.each(data.taskHandleListJsonList, function (index, user) {
            el.append('<label class="label-radio">'
                + '<input type="radio" name="' + name + '" value="' + user.id +  (index == 0 ? '" checked="checked">' : '">')
                + '<div class="form-checkbox"><img src="image/avatar/default-avatar.jpg">' + user.firstName + '</div>'
                + '</label>');
        });
    } else if (data.selectUserMode === 'multiUser') {
        el.children().remove();
        $$.each(data.taskHandleListJsonList, function (index, user) {
            el.append('<label class="label-checkbox">'
                + '<input type="checkbox" name="' + name + '" value="' + user.id +  (index == 0 ? '" checked="checked">' : '">')
                + '<div class="form-checkbox"><img src="image/avatar/default-avatar.jpg">' + user.firstName + '</div>'
                + '</label>');
        });
    } else if (data.selectUserMode === 'selectUser') {
        var obj = {};
        $$.each(data.taskHandleListJsonList, function (index, user) {
            obj[user.id] = {
                "Id": user.id,
                "job": user.jobInfo,
                "name": user.firstName
            };
        });
        updateUsers(obj);
    }
}

function buildHandleUserInput2(el, data, name) {
    var view = el.parents('.' + myApp.params.viewClass)[0] && el.parents('.' + myApp.params.viewClass)[0].f7View;
    if (!view) {
        return;
    }

    function updateUsers(users) {
        el.children().remove();
        $$.each(users, function (id, user) {
            el.append('<label class="label-checkbox">'
                + '<input type="checkbox" name="' +name + '" value="' + id + '" checked="checked" disabled>'
                + '<div class="form-checkbox"><img src="'+ user.avatar +'">' + user.name + '</div>'
                + '</label>');
        });
        if (el.children().length == 0) {
            el.append('<a href="#" class="button button-select-user">点击选择处理人</a>');
        } else {
            el.append('<label class="label-checkbox button-select-user">'
                + '<div class="form-checkbox"><img src="image/icon-add-user.png">添加</div>'
                + '</label>');
        }

        el.find('.button-select-user').click(function () {
            var callbackName = $$.uniqueName();
            //var users = {};
            window[callbackName] = {
                selectedUsers: users,
                delegate: updateUsers
            };

            view.router.load({url: (myApp.padApp ? 'selectUser-pad.html' : 'selectUser.html') + '?delegate=' + callbackName});
        });
    }

    if (data.selectUserMode === 'singleUser') {
        el.children().remove();
        $$.each(data.nextUserList, function (index, user) {
            el.append('<label class="label-radio">'
                + '<input type="radio" name="' + name + '" value="' + user.id +  (index == 0 ? '" checked="checked">' : '">')
                + '<div class="form-checkbox"><img src="image/avatar/default-avatar.jpg">' + user.firstName + '</div>'
                + '</label>');
        });
    } else if (data.selectUserMode === 'multiUser') {
        el.children().remove();
        $$.each(data.nextUserList, function (index, user) {
            el.append('<label class="label-checkbox">'
                + '<input type="checkbox" name="' + name + '" value="' + user.id +  (index == 0 ? '" checked="checked">' : '">')
                + '<div class="form-checkbox"><img src="image/avatar/default-avatar.jpg">' + user.firstName + '</div>'
                + '</label>');
        });
    } else if (data.selectUserMode === 'selectUser') {
        var obj = {};
        $$.each(data.taskHandleListJsonList, function (index, user) {
            obj[user.id] = {
                "Id": user.id,
                "job": user.jobInfo,
                "name": user.firstName
            };
        });
        updateUsers(obj);
    }
}

//日期时间选择器 yyyy-MM-dd HH:mm
function initDatePicker (input) {
    //console.log('initDatePicker: ' + type + ' ' + beginDate + ' ' + endDate);
    var today = new Date();
    function formatTime (time) {
        if (time < 10) {
            return '0' + time;
        }
        else {
            return time;
        }
    }
    var datetimePickerArg = {
        input: input,
        //container: '#picker-date-container',
        toolbar: true,
        rotateEffect: true,
        toolbarCloseText: '完成',

        value: [today.getFullYear(), (today.getMonth()+1), (today.getDate()), (today.getHours()), (today.getMinutes())],

        onChange: function (picker, values, displayValues) {
            var daysInMonth = new Date(picker.value[0], picker.value[1], 0).getDate();
            if (values[2] > daysInMonth) {
                picker.cols[4].setValue(daysInMonth);
            }
        },

        //onClose: function (picker) {
        //},

        formatValue: function (p, values, displayValues) {
            var s = (values[0] + '-' + formatTime(values[1]) + '-' + formatTime(values[2]) + ' ' + formatTime(values[3]) + ':' + formatTime(values[4]));
            return s;
        },

        cols: [
            // Years
            {
                values: (function () {
                    var arr = [];
                    for (var i = 1970; i <= 2030; i++) {
                        arr.push(i);
                    }
                    return arr;
                })(),
                textAlign: 'center'
            },
            // Space divider
            {
                divider: true,
                content: '-'
            },
            // Months
            {
                values: (function () {
                    var arr = [];
                    for (var i = 1; i <= 12; i++) {
                        arr.push(i);
                    }
                    return arr;
                })(),
                //values: ('0 1 2 3 4 5 6 7 8 9 10 11').split(' '),
                //displayValues: ('01 02 03 04 05 06 07 08 09 10 11 12').split(' '),
                textAlign: 'center'
            },
            // Space divider
            {
                divider: true,
                content: '-'
            },
            // Days
            {
                values: (function () {
                    var arr = [];
                    for (var i = 1; i <= 31; i++) {
                        arr.push(i);
                    }
                    return arr;
                })(),
                textAlign: 'center'
            },
            // Space divider
            {
                divider: true,
                content: '    '
            },
            // Hours
            {
                values: (function () {
                    var arr = [];
                    for (var i = 0; i <= 23; i++) {
                        arr.push(i);
                    }
                    return arr;
                })(),
                textAlign: 'center'
            },
            // Divider
            {
                divider: true,
                content: ':'
            },
            // Minutes
            {
                values: (function () {
                    var arr = [];
                    for (var i = 0; i <= 59; i++) {
                        arr.push(i);
                    }
                    return arr;
                })(),
                textAlign: 'center'
            }
        ]
    };
    myApp.picker(datetimePickerArg);
}

function buildComponents(list, components,fenfaCard) {
    $$.each(components, function (index, value) {
        var componentName = value.componentName;
        var li;
        value.required = value.required || value.validateType === 'notEmpty';       
        if(fenfaCard == 1){             	
        	value.type = 'display';
        }
        if (componentName == 'Select') {
            li = $$('<li><div class="item-content"><div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input"><select></select></div>' +
                '</div></div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('select').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('select').prop('disabled', true);
                li.find('.item-input').addClass('disabled');
            }
            $$.each(value.selectvalues, function (index, option) {
                li.find('select').append('<option value="' + option.key + '">' + option.value + '</option>');
            });
            li.find('select').val(value.value);
            list.append(li);
        } else if (componentName == 'Boolean') {
            li = $$('<li><div class="item-content"><div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input"><select></select></div>' +
                '</div></div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('select').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('select').prop('disabled', true);
                li.find('.item-input').addClass('disabled');
            }
            li.find('select').append('<option value="1">' + value.showValues.yesValue + '</option>');
            li.find('select').append('<option value="0">' + value.showValues.noValue + '</option>');
            li.find('select').val(value.value);
            list.append(li);
        } else if (componentName == 'MultiValue') {
            li = $$('<li><div class="item-content">' +
                '<div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<a href="#" class="smart-select" data-page-title="' + value.displayName + '"><select></select><div class="item-after"></div></a>' +
                '</div>' +
                '</div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('select').attr('name', value.columnName).attr('multiple', true);
            if (value.type === 'display') {
                li.find('select').prop('disabled', true);
                li.find('.smart-select').addClass('disabled');
            }
            $$.each(value.selectvalues, function (index, option) {
                if (value.value.indexOf(option.key) >= 0) {
                    li.find('.item-after').text(option.value);
                    li.find('select').append('<option value="' + option.key + '" selected>' + option.value + '</option>');
                } else {
                    li.find('select').append('<option value="' + option.key + '">' + option.value + '</option>');
                }
            });
            list.append(li);
        } else if (componentName == 'ShortText') {
            li = $$('<li><div class="item-content"><div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input">' +
                '<input type="text">' +
                '</div>' +
                '</div></div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('input').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('input').prop('disabled', true);
                li.find('.item-input').addClass('disabled');
            }
            li.find('input').val(value.value);
            list.append(li);
        } else if (componentName == 'LongText') {
            li = $$('<li class="align-top">' +
                '<div class="item-content">' +
                '<div class="item-inner item-inner-long">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input">' +
                '<textarea class="resizable"></textarea>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('textarea').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('textarea').prop('disabled', true);
                li.find('.item-input').addClass('disabled');
            }
            li.find('textarea').val(value.value);
            list.append(li);
        } else if (componentName == 'Timestamp' || componentName == 'CurrentDate') {
            var inputType = value.onlyDate == 'true' ? 'date' : 'datetime-local';
            li = $$('<li><div class="item-content"><div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input"><input type="' + inputType + '"></div>' +
                '</div></div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('input').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('input').prop('disabled', true);
                li.find('.item-input').addClass('disabled');
            }
            var ms = Date.parse(value.value);
            var date;
            if (!isNaN(ms)) {
                date = new Date(ms);
            } else if (componentName == 'CurrentDate') {
                date = new Date();
            }
            if (date) {
                li.find('input').val(date.Format((inputType == 'date' ? 'yyyy-MM-dd' : 'yyyy-MM-ddThh:mm')));
            }
            list.append(li);
        } else if (componentName == 'KeyWord') {
            li = $$('<li class="align-top">' +
                '<div class="item-content">' +
                '<div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input input-dropdown">' +
                '<textarea class="resizable"></textarea><a class="dropdown-toggle" href="#"><i class="icon"></i></a>' +
                '<ul></ul>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('textarea').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('textarea').prop('disabled', true);
                li.find('.item-input').addClass('disabled');
            }
            li.find('textarea').val(value.value);
            $$.each(value.selectvalues, function (index, keyword) {
                li.find('ul').append('<li><a class="dropdown-option ' + (keyword.value == value.value ? 'selected' : '') + '" href="#">' +
                    '<i>●&nbsp;&nbsp;</i><span>' + keyword.value + '</span></a></li>');
            });
            list.append(li);
        } else if (componentName == 'NewHtmlText') {
            li = $$('<li class="align-top">' +
                    '<div class="item-content">' +
                        '<div class="item-inner item-inner-long">' +
                            '<div class="item-title label"></div>' +
                            '<div class="item-input disabled" style="display: block"></div>' +
                            '<textarea class="resizable" style="display: none"></textarea>' +
                        '</div>' +
                    '</div>' +
                '</li>');
            li.find('.item-title').text(value.displayName);
            li.find('.item-input').html(value.value);
            li.find('textarea').attr('name', value.columnName);
            li.find('textarea').val(value.value);
            list.append(li);
        } /*else if (componentName == 'DocType') {
         li = $$('<li><div class="item-content"><div class="item-inner">' +
         '<div class="item-title label"></div>' +
         '<div class="item-input"><select></select></div>' +
         '</div></div></li>');
         li.find('.item-title').text(value.displayName);
         var select = li.find('select');
         select.attr('name', value.columnName);
         select.prop('disabled', value.type == 'display');

         var map = eval('(' + value.jsonObjectType + ')');
         (function buildMap(element, obj) {
         $$.each(obj, function (key, value) {
         if ($$.isArray(value)) {
         var group = $$('<optgroup label="' + key + '"></optgroup>');
         element.append(group);
         $$.each(value, function (index, value) {
         var el = $$('<option value="' + value + '">' + value + '</option>');
         group.append(el);
         });
         } else {
         var group = $$('<optgroup label="' + key + '"></optgroup>');
         element.append(group);
         buildMap(group, value);
         }
         });
         }(select, map));
         select.val(value.value);

         list.append(li);
         } */ else if (componentName == 'UserChoose') {
            li = $$('<li><div class="item-content">' +
                '<div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<a href="#" class="custom-select"><input type="text" select-type="users"><div class="item-after"></div></a>' +
                '</div>' +
                '</div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('input').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('input').prop('disabled', true);
                li.find('.custom-select').addClass('disabled');
            }
            li.find('input').val(value.userValues);
            li.find('.item-after').text(value.userNames);
            var array = value.selectUser ? value.selectUser.split(',') : [];
            var obj = {};
            for (var i = 0; i < array.length; i++) {
                var fields = array[i].split('|');
                obj[fields[0]] = {
                    "id": fields[0],
                    "name": fields[2],
                    "firstName": fields[1]
                };
            }
            li.find('input').data('users', obj);
            list.append(li);
        } else if (componentName == 'DepartChoose') {
            li = $$('<li><div class="item-content">' +
                '<div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<a href="#" class="custom-select"><input type="text" select-type="departs"><div class="item-after"></div></a>' +
                '</div>' +
                '</div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('input').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('input').prop('disabled', true);
                li.find('.custom-select').addClass('disabled');
            }
            li.find('input').val(value.departIds);
            li.find('.item-after').text(value.departNames);
            var array = value.selectDepart ? value.selectDepart.split(',') : [];
            var obj = {};
            for (var i = 0; i < array.length; i++) {
                var fields = array[i].split('|');
                obj[fields[0]] = {
                    "id": fields[0],
                    "label": fields[1]
                };
            }
            li.find('input').data('departs', obj);
            list.append(li);
        } else if (componentName == 'CurrentUser') {
            li = $$('<li><div class="item-content"><div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input disabled"><select disabled></select></div>' +
                '</div></div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('select').attr('name', value.columnName);
            var user = value.value || {FIRSTNAME: CURRENT_USER.firstName, ID: CURRENT_USER.loginid};
            li.find('select').append('<option value="' + user.ID + '">' + user.FIRSTNAME + '</option>');
            li.find('select').val(value.value);
            list.append(li);
        } else if (componentName == 'CurrentDepart') {
            li = $$('<li><div class="item-content"><div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input"><select></select><a class="dropdown-toggle" href="#" style="position: absolute; right: 10px; pointer-events: none"><i class="icon"></i></a></div>' +
                '</div></div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('select').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('select').prop('disabled', true);
                li.find('.item-input').addClass('disabled');
                li.find('.dropdown-toggle').hide();
            }
            $$.each(value.departList, function (index, depart) {
                li.find('select').append('<option value="' + depart.DEPARTID + '">' + depart.DEPARTNAME + '</option>');
            });
            li.find('select').val(value.value);
            list.append(li);
        } else if (componentName == 'DocType' || componentName == 'DocNoDemo') {
            li = $$('<li><div class="item-content"><div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input disabled">' +
                '<input type="text" disabled>' +
                '</div>' +
                '</div></div></li>');
            li.find('.item-title').text(value.displayName);
            li.find('input').attr('name', value.columnName);
            li.find('input').val(value.value);
            list.append(li);
        } else if (componentName == 'MultiConfirmAdvice') {
            li = $$('<li class="align-top">' +
                '<div class="item-content">' +
                '<div class="item-inner item-inner-long">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input item-input-advice disabled">' +
                '<textarea class="resizable" disabled></textarea>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</li>');
            if(value.value != null) {
           	 	li.find('.item-input-advice').html('<input type="hidden" name="'+value.columnName+'"  value="'+value.confirmId+'">');
            }   
            li.find('.item-title').text(value.displayName);
            li.find('textarea').attr('name', value.columnName);
            $$.each(value.value, function (index, advice) {
                if (advice.confirmInfo) {
                    if (advice.hasImg == 'true') {
                        li.find('.item-input').append('<p><img width="100%" height="" src="' + WEB_CONTEXT_PATH + advice.confirmInfo + '"></p>');
                    } else {
                        li.find('.item-input').append('<p>' + advice.confirmInfo + '</p>');
                    }
                    if (!((typeof advice.confirmUserJobInfo =="undefined") || (advice.confirmUserJobInfo == null))){
                   	    li.find('.item-input').append('<p style="text-align: right">' + "----" + ' ' + advice.confirmUserJobInfo + '</p>');
                   	    li.find('.item-input').append('<p style="text-align: right">' + advice.confirmUser + '</p>');
                    }else{
                   	    li.find('.item-input').append('<p style="text-align: right">' + "----" + ' ' + advice.confirmUser + '</p>');
                    }                                       
                    li.find('.item-input').append('<p style="text-align: right">' + advice.confirmDate + '</p>');
                }
            });
            list.append(li);
        }
        // for meeting
        else if (componentName == 'MeetingHidden') {
            li = $$('<li><div class="item-content"><div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input">' +
                '<input type="text">' +
                '</div>' +
                '</div></div></li>');
            li.hide();
            li.find('input').attr('name', value.columnName);
            li.find('input').val(value.value);
            list.append(li);
        } else if (componentName == 'MeetingDateTime') {
            li = $$('<li><div class="item-content"><div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input"><input type="text" readonly></div>' +
                '</div></div></li>');
            initDatePicker(li.find('input'));
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('input').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('input').prop('disabled', true);
                li.find('.item-input').addClass('disabled');
            }
            li.find('input').val(value.value);
            list.append(li);
        } else if (componentName == 'MeetingCheckBox') {
            var deviceComp = value,
                checkedDevice = deviceComp.value.split(',');
            var divider = $$('<li class="item-divider">' + deviceComp.displayName + '</li>');
            list.append(divider);
            $$.getJSONP(SERVER_PATH + 'getMeetingDevices.do', function (json) {
                if (json.code == 1 && json.results.length > 0) {
                    $$.each(json.results.reverse(), function (index, value) {
                        var li = $$('<li><label class="label-checkbox item-content">' +
                            '<input type="checkbox">' +
                            '<div class="item-media">' +
                            '<i class="icon icon-form-checkbox"></i>' +
                            '</div>' +
                            '<div class="item-inner">' +
                            '<div class="item-title"></div>' +
                            '</div>' +
                            '</label></li>');
                        li.find('.item-title').text(value.text);
                        li.find('input').attr('name', deviceComp.columnName);
                        li.find('input').prop('disabled', value.type === 'display');
                        li.find('input').val(value.value);
                        if (checkedDevice.indexOf(value.value) >= 0) {
                            li.find('input').prop('checked', true);
                        }
                        li.insertAfter(divider);
                    });
                }
            });
        } else if (componentName == 'MeetingSelectUser') {
            li = $$('<li><div class="item-content">' +
                '<div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<a href="#" class="custom-select"><input type="text" select-type="meeting-users"><div class="item-after"></div></a>' +
                '</div>' +
                '</div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('input').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('input').prop('disabled', true);
                li.find('.custom-select').addClass('disabled');
            }
            li.find('input').val(value.value);
            li.find('.item-after').text(value.value);
            list.append(li);
        } else if (componentName == 'MeetingSelectRoom') {
            li = $$('<li><div class="item-content">' +
                '<div class="item-inner">' +
                '<div class="item-title label"></div>' +
                '<a href="#" class="custom-select"><input type="text" select-type="meeting-room"><div class="item-after"></div></a>' +
                '</div>' +
                '</div></li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            li.find('input').attr('name', value.columnName);
            if (value.type === 'display') {
                li.find('input').prop('disabled', true);
                li.find('.custom-select').addClass('disabled');
            }
            li.find('input').val(value.value);
            li.find('.item-after').text(value.value);
            list.append(li);
        } else if (componentName == 'MeetingAdvice') {
            li = $$('<li class="align-top">' +
                '<div class="item-content">' +
                '<div class="item-inner item-inner-long">' +
                '<div class="item-title label"></div>' +
                '<div class="item-input item-input-advice disabled">' +
                '<textarea class="resizable" disabled></textarea>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</li>');
            li.find('.item-title').html((value.type === 'edit' && value.required ? '<span class="required-comp">*</span>' : '') + value.displayName);
            $$.each(value.value, function (index, advice) {
                li.find('.item-input').append('<p>' + advice.content + '</p>');
                li.find('.item-input').append('<p style="text-align: right">' + advice.user + '  ' + advice.date + '</p>');
            });
            list.append(li);
        } else {
            console.log('[ERROR] Unhandled form component ' + componentName);
        }

        if (value.alone === false) {
            li.addClass('half-row');
        }
    });
}


$$(document).on('click', function (e) {
    var clicked = $$(e.target);
    if (!clicked.hasClass('nav-dropdown-toggle') && clicked.parents('.nav-dropdown-toggle').length === 0) {
        $$('.nav-dropdown').removeClass('nav-open');
    }
});
$$(document).on('click', '.nav-dropdown .nav-dropdown-toggle', function (e) {
    $$(this).parents('.nav-dropdown').toggleClass('nav-open');
});


// custom pull to refresh
(function () {
    var app = myApp;
    var $ = Dom7;
    app.initPullToRefresh = function (pageContainer) {
        var eventsTarget = $(pageContainer);
        if (!eventsTarget.hasClass('pull-to-refresh-content')) {
            eventsTarget = eventsTarget.find('.pull-to-refresh-content');
        }
        if (!eventsTarget || eventsTarget.length === 0) return;

        var touchId, isTouched, isMoved, touchesStart = {}, isScrolling, touchesDiff, touchStartTime, container, refresh = false, useTranslate = false, startTranslate = 0, translate, scrollTop, wasScrolled, layer, triggerDistance, dynamicTriggerDistance;
        var page = eventsTarget.hasClass('page') ? eventsTarget : eventsTarget.parents('.page');
        var hasNavbar = false;
        if (page.find('.navbar').length > 0 || page.parents('.navbar-fixed, .navbar-through').length > 0 || page.hasClass('navbar-fixed') || page.hasClass('navbar-through')) hasNavbar = true;
        if (page.hasClass('no-navbar')) hasNavbar = false;
        if (!hasNavbar) eventsTarget.addClass('pull-to-refresh-no-navbar');

        container = eventsTarget;
        var car = container.find('.pull-to-refresh-car');

        // Define trigger distance
        if (container.attr('data-ptr-distance')) {
            dynamicTriggerDistance = true;
        }
        else {
            triggerDistance = 80;
        }

        function handleTouchStart(e) {
            if (isTouched) {
                if (app.device.os === 'android') {
                    if ('targetTouches' in e && e.targetTouches.length > 1) return;
                }
                else return;
            }

            isMoved = false;
            isTouched = true;
            isScrolling = undefined;
            wasScrolled = undefined;
            if (e.type === 'touchstart') touchId = e.targetTouches[0].identifier;
            touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
            touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
            touchStartTime = (new Date()).getTime();
            /*jshint validthis:true */
            container = $(this);
        }

        function handleTouchMove(e) {
            if (!isTouched) return;
            var pageX, pageY, touch;
            if (e.type === 'touchmove') {
                if (touchId && e.touches) {
                    for (var i = 0; i < e.touches.length; i++) {
                        if (e.touches[i].identifier === touchId) {
                            touch = e.touches[i];
                        }
                    }
                }
                if (!touch) touch = e.targetTouches[0];
                pageX = touch.pageX;
                pageY = touch.pageY;
            }
            else {
                pageX = e.pageX;
                pageY = e.pageY;
            }
            if (!pageX || !pageY) return;


            if (typeof isScrolling === 'undefined') {
                isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x));
            }
            if (!isScrolling) {
                isTouched = false;
                return;
            }

            scrollTop = container[0].scrollTop;
            if (typeof wasScrolled === 'undefined' && scrollTop !== 0) wasScrolled = true;

            if (!isMoved) {
                /*jshint validthis:true */
                container.removeClass('transitioning');
                if (scrollTop > container[0].offsetHeight) {
                    isTouched = false;
                    return;
                }
                if (dynamicTriggerDistance) {
                    triggerDistance = container.attr('data-ptr-distance');
                    if (triggerDistance.indexOf('%') >= 0) triggerDistance = container[0].offsetHeight * parseInt(triggerDistance, 10) / 100;
                }
                startTranslate = container.hasClass('refreshing') ? triggerDistance : 0;
                if (container[0].scrollHeight === container[0].offsetHeight || app.device.os !== 'ios') {
                    useTranslate = true;
                }
                else {
                    useTranslate = false;
                }
            }
            isMoved = true;
            touchesDiff = pageY - touchesStart.y;

            if (touchesDiff > 0 && scrollTop <= 0 || scrollTop < 0) {
                // iOS 8 fix
                if (app.device.os === 'ios' && parseInt(app.device.osVersion.split('.')[0], 10) > 7 && scrollTop === 0 && !wasScrolled) useTranslate = true;

                if (useTranslate) {
                    e.preventDefault();
                    translate = (Math.pow(touchesDiff, 0.85) + startTranslate);
                    container.transform('translate3d(0,' + translate + 'px,0)');
                    car.css({left: (translate * container.width() / triggerDistance) + 'px'});
                }
                else {
                }
                if ((useTranslate && Math.pow(touchesDiff, 0.85) > triggerDistance) || (!useTranslate && touchesDiff >= triggerDistance * 2)) {
                    refresh = true;
                    container.addClass('pull-up').removeClass('pull-down');
                }
                else {
                    refresh = false;
                    container.removeClass('pull-up').addClass('pull-down');
                }
            }
            else {

                container.removeClass('pull-up pull-down');
                refresh = false;
                return;
            }
        }

        function handleTouchEnd(e) {
            if (e.type === 'touchend' && e.changedTouches && e.changedTouches.length > 0 && touchId) {
                if (e.changedTouches[0].identifier !== touchId) return;
            }
            if (!isTouched || !isMoved) {
                isTouched = false;
                isMoved = false;
                return;
            }
            if (translate) {
                container.addClass('transitioning');
                translate = 0;
            }
            container.transform('');
            if (refresh) {
                container.addClass('refreshing');
                container.trigger('refresh', {
                    done: function () {
                        app.pullToRefreshDone(container);
                    }
                });
            }
            else {
                container.removeClass('pull-down');
            }
            isTouched = false;
            isMoved = false;
        }

        // Attach Events
        eventsTarget.on(app.touchEvents.start, handleTouchStart);
        eventsTarget.on(app.touchEvents.move, handleTouchMove);
        eventsTarget.on(app.touchEvents.end, handleTouchEnd);

        // Detach Events on page remove
        if (page.length === 0) return;
        function destroyPullToRefresh() {
            eventsTarget.off(app.touchEvents.start, handleTouchStart);
            eventsTarget.off(app.touchEvents.move, handleTouchMove);
            eventsTarget.off(app.touchEvents.end, handleTouchEnd);
        }

        eventsTarget[0].f7DestroyPullToRefresh = destroyPullToRefresh;
        function detachEvents() {
            destroyPullToRefresh();
            page.off('pageBeforeRemove', detachEvents);
        }

        page.on('pageBeforeRemove', detachEvents);

    };
}());